package com.smartbus.bus.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.smartbus.common.annotation.Log;
import com.smartbus.common.core.controller.BaseController;
import com.smartbus.common.core.domain.AjaxResult;
import com.smartbus.common.enums.BusinessType;
import com.smartbus.bus.domain.Buses;
import com.smartbus.bus.domain.dto.DispatchVehicleDTO;
import com.smartbus.bus.service.IBusesService;
import com.smartbus.common.utils.poi.ExcelUtil;
import com.smartbus.common.core.page.TableDataInfo;

/**
 * 车辆调度系统Controller
 * 专门为调度系统提供车辆相关API
 *
 * @author smartbus
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/bus/vehicles")
public class VehiclesController extends BaseController
{
    @Autowired
    private IBusesService busesService;

    /**
     * 查询车辆列表
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:list')")
    @GetMapping("/list")
    public TableDataInfo list(Buses buses)
    {
        startPage();
        List<Buses> list = busesService.selectBusesList(buses);
        return getDataTable(list);
    }

    /**
     * 查询车辆详细信息
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(busesService.selectBusesById(id));
    }

    /**
     * 新增车辆
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:add')")
    @Log(title = "车辆管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Buses buses)
    {
        return toAjax(busesService.insertBuses(buses));
    }

    /**
     * 修改车辆信息
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:edit')")
    @Log(title = "车辆管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Buses buses)
    {
        return toAjax(busesService.updateBuses(buses));
    }

    /**
     * 删除车辆
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:remove')")
    @Log(title = "车辆管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(busesService.deleteBusesByIds(ids));
    }

    /**
     * 获取调度系统车辆数据（包含实时位置、状态等）
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:list')")
    @GetMapping("/dispatch")
    public AjaxResult getDispatchVehicles()
    {
        try {
            List<DispatchVehicleDTO> dispatchVehicles = busesService.getDispatchVehicles();
            return AjaxResult.success("获取调度车辆数据成功", dispatchVehicles);
        } catch (Exception e) {
            logger.error("获取调度车辆数据失败", e);
            return AjaxResult.error("获取调度车辆数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取车辆实时位置
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:list')")
    @GetMapping("/realtime")
    public AjaxResult getVehicleRealTimeLocation()
    {
        try {
            List<DispatchVehicleDTO> realtimeData = busesService.getVehicleRealTimeLocation();
            return AjaxResult.success("获取车辆实时位置成功", realtimeData);
        } catch (Exception e) {
            logger.error("获取车辆实时位置失败", e);
            return AjaxResult.error("获取车辆实时位置失败: " + e.getMessage());
        }
    }

    /**
     * 更新车辆位置（模拟GPS上报）
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:edit')")
    @Log(title = "车辆位置更新", businessType = BusinessType.UPDATE)
    @PostMapping("/location")
    public AjaxResult updateVehicleLocation(@RequestBody Map<String, Object> locationData)
    {
        try {
            int result = busesService.updateVehicleLocation(locationData);
            if (result > 0) {
                return AjaxResult.success("车辆位置更新成功");
            } else {
                return AjaxResult.error("车辆位置更新失败");
            }
        } catch (Exception e) {
            logger.error("更新车辆位置失败", e);
            return AjaxResult.error("更新车辆位置失败: " + e.getMessage());
        }
    }

    /**
     * 获取车辆运营统计
     */
    @PreAuthorize("@ss.hasPermi('bus:buses:list')")
    @GetMapping("/stats")
    public AjaxResult getVehicleStats()
    {
        try {
            Map<String, Object> stats = busesService.getVehicleStats();
            return AjaxResult.success("获取车辆统计数据成功", stats);
        } catch (Exception e) {
            logger.error("获取车辆统计数据失败", e);
            return AjaxResult.error("获取车辆统计数据失败: " + e.getMessage());
        }
    }
}